package angry.courses.beans;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import angry.courses.entities.StudentEntity;

@Stateless
public class StudentDAOBean implements StudentDAO {
	@PersistenceContext
	private EntityManager em;
	
	public void create(StudentEntity student) {
		em.persist(student);
	}

	public StudentEntity retrieve(int sid) {
		StudentEntity student = null;
		try {
			Query query = em.createNamedQuery("retrieveStudentById");
			query.setParameter("sid", sid);
			student = (StudentEntity) query.getSingleResult();
		} catch(Exception e) {
			student = null;
		}
		return student;
	}
	
	public StudentEntity retrieve(String regNr) {
		StudentEntity student = null;
		try {
			Query query = em.createNamedQuery("retrieveStudent");
			query.setParameter("regnr", regNr);
			student = (StudentEntity) query.getSingleResult();
		} catch(Exception e) {
			student = null;
		}
		return student;
	}
	
	public List<StudentEntity> retrieveStudents() {
		List<StudentEntity> students = null;
		try {
			Query query = em.createNamedQuery("retrieveStudents");
			students = (List<StudentEntity>) query.getResultList();
		} catch(Exception e) {
			students = null;
		}
		return students;
	}
	
	public void remove(StudentEntity student) {
		StudentEntity existing = em.find(StudentEntity.class, student.getID());
		em.remove(existing);
	}

	public void modify(StudentEntity student) {
		StudentEntity existing = em.find(StudentEntity.class, student.getID());
		em.merge(existing);
	}
	
	public StudentEntity retrieveByName(String name) {
		StudentEntity student = null;
		try {
			Query query = em.createNamedQuery("retrieveStudentByName");
			query.setParameter("name", name);
			student = (StudentEntity) query.getSingleResult();
		} catch(Exception e) {
			student = null;
		}
		return student;
	}
}
